#!/usr/bin/perl
#
# ColdSync conduit. Converts the Palm ToDo list to and from a simple text
# format.
#
#	Copyright (C) 2000, Andrew Arensburger.
#	You may distribute this file under the terms of the Artistic
#	License, as specified in the README file.
#
# $Id: todo-text,v 1.9 2001-06-04 10:19:34 arensb Exp $

# XXX - Make sure this works when Note-Indent and/or Item-Cont are empty
# strings

# XXX - When syncing a category whose name is empty, use #NNN, where NNN is
# the category ID.

use strict;
use Palm::ToDo;
use ColdSync;
use Text::Wrap;		# Used for pretty-printing
use vars qw( @SORTED );	# List of records, sorted by category and priority

# Set default values
%HEADERS = (
	"Where"		=> "$ENV{HOME}/ToDo",	# Directory to sync with
	"Item-Prefix"	=> "- ",	# Start of unfinished item
	"Done-Prefix"	=> "* ",	# Start of completed item
	"Item-Cont"	=> "  ",	# Continuation of item description
	"Note-Indent"	=> "  ",	# Continuation of note
	"Paragraph"	=> "\t",	# Marks new paragraph in note
	"Delete"	=> "no",	# How to deal with deleted records
					# [yes|no|expunge|archive]
					# yes == archive
);

my $VERSION = (qw( $Revision: 1.9 $ ))[1];	# Cute hack for conduit version

ConduitMain(
	"fetch"		=> \&DoFetch,
	"dump"		=> \&DoDump,
);

sub DoFetch
{
	# XXX - Create the OutputDB if necessary

	my $category;
	my %cat_name2index;		# Maps category names to indices

	# Sanity check on arguments
	$HEADERS{Delete} = lc($HEADERS{Delete});
	if ($HEADERS{Delete} ne "yes" and
	    $HEADERS{Delete} ne "no" and
	    $HEADERS{Delete} ne "archive" and
	    $HEADERS{Delete} ne "expunge")
	{
		warn "403 Illegal \"Delete\" header. Using default: \"no\"\n";
		$HEADERS{Delete} = "no";
	}

	if (! -d $HEADERS{Where})
	{
		die "401 $HEADERS{Where} is not a directory.\n";
	}

	# Initialize category index

	# XXX - What happens when there are files named after nonexistent
	# categories? Or other boundary conditions?
	my $i;
	for ($i = 0; $i <= $#{$PDB->{appinfo}{categories}}; $i++)
	{
		$cat_name2index{$PDB->{appinfo}{categories}[$i]{name}} = $i;
	}

	# Read and parse each file in turn
	opendir CATEGORIES, $HEADERS{Where};
	while ($category = readdir(CATEGORIES))
	{
		my $priority = 1;

		next if $category eq ".";
		next if $category eq "..";
		next if $category =~ /(\.bak|~)$/;	# Ignore backup files

		my @items;
		my $item;

		@items = &collect($HEADERS{Where}, $category);

		foreach $item (@items)
		{
			my $record;	# Record in PDB

			$record = &find_record($PDB,
					       $category,
					       $item->{title});
			if (!defined($record))
			{
				# This is a new item
				$record = $PDB->append_Record;
				$record->{category} =
					$cat_name2index{$category};
				$record->{completed} = $item->{completed};
				$record->{priority} = $priority;
				$record->{description} = $item->{title};
				$record->{note} = $item->{note}
					if $item->{note} ne "";
				$record->{_seen} = 1;
					# Mark this record as seen
			} else {
				# This is an existing record. Update it if
				# necessary. If so, mark it as dirty.

				if ($record->{completed} xor
				    $item->{completed})
				{
					$record->{completed} =
						$item->{completed};
					$record->{attributes}{dirty} = 1;
				}

				if ($record->{note} ne $item->{note})
				{
					$record->{note} = $item->{note};
					$record->{attributes}{dirty} = 1;
				}

				# The description is the same, we know
				# that. Also, we don't touch the record's
				# priority or due date.

				$priority = $record->{priority};
					# Record this record's priority
					# for the next item
				$record->{_seen} = 1;
					# Mark this record as seen
			}
		}

	}

	# Delete all unseen records
	my $record;

	return 1 if ($HEADERS{Delete} eq "no");

	foreach $record (@{$PDB->{records}})
	{
		next if $record->{_seen};
		if ($HEADERS{Delete} eq "expunge")
		{
			$PDB->delete_Record($record, 1);	# Expunge
		} else {
			# $HEADERS{Delete} is "yes", "archive", undefined,
			# or some illegal value.
			$PDB->delete_Record($record, 0);
		}
	}

	return 1;
}

# collect
# Read all of the items in a file, and return them as an array of records.
sub collect
{
	my $dir = shift;
	my $category = shift;
	my @retval = ();
	my $item = {};		# Dummy initial item
	my $title_cont = 0;	# Flag: are we expecting the nth line of a
				# todo item title?

	open IN, "< $dir/$category" or
		die "401 Can't open $dir/$category: $!\n";
	while (<IN>)
	{
		chomp;

		return @retval if $_ eq "__END__";

		my $intitle = 0;	# True if we're looking at a title
					# line (not a note line)

		if ($title_cont)
		{
			# This line is the continuation of the current
			# item's title

			s/^\Q$HEADERS{"Item-Cont"}\E//;
			$intitle = 1;
		}

		if (/^\Q$HEADERS{"Item-Prefix"}\E/)
		{
			# This is a new todo item
			$item = {};
			push @retval, $item;
			$item->{completed} = 0;	# Item hasn't been
						# completed yet

			$_ = $';
			$intitle = 1;
		}

		if (/^\Q$HEADERS{"Done-Prefix"}\E/)
		{
			# This is a new todo item
			$item = {};
			push @retval, $item;
			$item->{completed} = 1;	# Item has been completed

			$_ = $';
			$intitle = 1;
		}

		# Common processing for all title lines.
		if ($intitle)
		{
			# Unescape backslashed characters
			s/\\(.)/$1/g;

			# Is there a continuation line after this one?
			if (/\\$/)
			{
				# Line ends in "\", so yes.
				chop;
				$_ .= "\n";
				$title_cont = 1;
			} else {
				# Nope.
				$title_cont = 0;
			}

			$item->{title} .= $_;
			next;
		}

		# If this line wasn't caught by any of the other clauses,
		# it must be the note attached to a todo item.

		# Unescape backslashed characters
		s/\\(.)/$1/g;

		if (/^\Q$HEADERS{"Paragraph"}/ or
		    /^\s*$/)		# Blank line
		{
			# This is the start of a new paragraph
			$_ = $';
			$item->{note} .= "\n" if $item->{note} ne "";
			$item->{note} .= $_;
		} else {
			s/^\Q$HEADERS{"Note-Indent"}\E//;
			$item->{note} .= " "
				unless $item->{note} eq "" or
					$item->{note} =~ /\n$/;
			$item->{note} .= $_;
		}
	}
	close IN;

	return @retval;
}

# find_record
# Find the record in the given category with the given description, and
# return it. Returns undef if not found.
# Assumes that (category, description) is a unique key. This may be a bad
# assumption.
sub find_record
{
	my $PDB = shift;
	my $category = shift;		# Category name to look in
	my $desc = shift;		# Description, used as unique key
	my $record;

	foreach $record (@{$PDB->{records}})
	{
		next unless
			$PDB->{appinfo}{categories}[$record->{category}]{name}
			eq $category;
		next unless $record->{description} eq $desc;

		# Return the first matching record. This is arguably the
		# Wrong Thing to do, but hey.
		return $record;
	}

	return undef;		# Not found
}

sub DoDump
{
	my $i;

	# Make sure the destination directory exists
	if (! -e $HEADERS{Where})
	{
		# The destination directory doesn't exist. Create it.
		mkdir $HEADERS{Where}, 0700 or
			die "501 Can't create destination directory $HEADERS{Where}: $!\n";
	} elsif (! -d $HEADERS{Where})
	{
		die "502 $HEADERS{Where} isn't a directory.\n";
	}

	# Begin by sorting by priority. That way, the output file will be
	# sorted by decreasing priority.
	@SORTED = sort { $a->{priority} <=> $b->{priority} }
		@{$PDB->{records}};

	# Dump each category in turn, since each category goes into a
	# separate file.
	for ($i = 0; $i < $#{$PDB->{appinfo}{categories}}; $i++)
	{
		# Ignore nonexistent categories
		next if $PDB->{appinfo}{categories}[$i]{name} eq "";

		# XXX - Ought to a) copy the file to a .bak file, and also
		# b) overwrite the original file. (a) will allow us to
		# preserve the header and footer lines, and (b) doesn't
		# break symlinks.

		# Find all of the records in this category, and dump them
		# to a file.
		&DumpCategory($PDB,
			      $PDB->{appinfo}{categories}[$i]{name},
			      grep { $_->{category} == $i } @SORTED);
	}

	return 1;
}

# DumpCategory
# Dump all of the records in a given category to a file in $HEADERS{Where}
# named after the category.
# ** Appearances to the contrary, this is not a method **
sub DumpCategory
{
	my $PDB = shift;
	my $catname = shift;		# Category name
	my @records = @_;		# Records to dump
	my $outfname = "$HEADERS{Where}/$catname";
					# Output filename
	my $record;			# Current record

	open OUT, "> $outfname" or do {
		warn "Can't open $outfname for writing: $!.\n",
		     "Skipping this category\n";
		return -1;
	};

	# Process each record in turn
	foreach $record (@records)
	{
		if ($record->{completed})
		{
			print OUT $HEADERS{"Done-Prefix"};
		} else {
			print OUT $HEADERS{"Item-Prefix"};
		}

		my $desc = $record->{description};

		# There have to be two expressions here, to deal with
		# the border case where the description ends in \n.
		$desc =~ s/\n|\\/\\$&/gs;
			# Escape each \n
  		$desc =~ s/\n(?=.)/\n$HEADERS{"Item-Cont"}/gs;
			# Replace end of line with "\n  " (newline plus
			# prefix for new line), except for the last line.
		print OUT $desc, "\n";

		my $note = $record->{note};
		my @paragraphs;

		next if $note eq "";
		@paragraphs = split /\n/, $note;
		for (@paragraphs)
		{
			# Pretty-print each paragraph with
			# Text::Wrap::wrap().
			print OUT wrap($HEADERS{Paragraph},
				$HEADERS{"Note-Indent"}, $_),
				"\n";
		}
		print OUT $HEADERS{Paragraph}, "\n"
			if $note =~ /\n$/;	# Boundary condition
	}

	close OUT;
}

__END__

=head1 NAME

todo-text - ColdSync conduit that converts to do lists to/from plain text

=head1 SYNOPSIS

Add the following to your F<.coldsyncrc> file:

	conduit fetch, dump {
		type: todo/DATA;
		path: "<...>/todo-text";
	    arguments:
		Where:	/home/arensb/todo;
		Delete:	yes;
	}

or run C<todo-text -conduit>.

=head1 DESCRIPTION

The C<todo-text> conduit converts to do lists between the built-in Palm
ToDo application, and a rather simple text format. Here is an example of
the sort of file that C<todo-text> generates:

	- Build latest version of GNOME
		Official site is http://www.gnome.org/ . Get it at night,
	  when there are fewer users.
	- Invite Stan for frisbee
	* Shopping
		Ramen
		Jolt
		Altoids
		Popcorn

This format should be fairly self-explanatory. The first line of an item is
its description; subsequent lines are the attached note, if any. A tab
marks the beginning of a new paragraph.

In the example above, the third item is marked with a star (C<*>), meaning
that this item has been completed.

The aim is simplicity, not completeness. Hence, this format ignores due
dates and provides only rudimentary support for priorities. See
L<"LIMITATIONS">, below.

=head2 Headers and Footers

Anything before the first "C<- >" or "C<* >" is ignored. In principle, you
could use this feature for custom headers.

If a text file contains "C<__END__>" on a line by itself, C<todo-text> will
ignore that line and anything after it when it runs as a Fetch conduit.

In the current implementation, C<todo-text> clobbers these headers and
footers when it runs as a Dump conduit, so their usefulness is minimal.

=head1 ARGUMENTS

=over 4

=item Where

This indicates the path to a directory where C<todo-text> will store the to
do lists.

=item Delete

The C<Delete> argument is only used when C<todo-text> is run as a Fetch
conduit. It determines what happens to those to do items that appear in the
PDB, but not in the text file (presumably these are the items that you have
deleted from the text file).

This argument can take on one of four values: C<yes>, C<no>, C<archive>, or
C<expunge>.

C<no> means not to touch those items at all. The text file updates the PDB,
but when C<todo-text> runs as a Dump conduit, the "deleted" items will show
up in the text file again. C<no> is the default.

C<expunge> means to delete the "deleted" items without keeping a backup.

C<yes> and C<archive> are synonymous. This means to remove the "deleted"
items from the PDB, but to keep a copy in the C<ToDoDB> archive file,
F<~/.palm/archive/ToDoDB> by default.

The first time around, you should set

	Delete: no

so that the text files and PDB contain all of your to do items. After the
next sync, though, you should change it to either C<archive> or C<expunge>
so that you don't have to delete items in two places each time.

=item Item-Prefix

=item Done-Prefix

=item Item-Cont

=item Note-Indent

=item Paragraph

These arguments affect the way the items are printed to the text files. I
won't explain them in detail, because they are set to sane values by
default, and the current version of ColdSync (1.4.5 as of this writing)
doesn't allow you to set them to other sane values.

=back

=head1 LIMITATIONS

(aka "Bugs that I don't intend to fix".)

C<todo-text> doesn't deal with due dates, mainly because I don't use them.
If an existing item has a due date attached, C<todo-text> doesn't modify
it, though.

C<todo-text> deals with priorities in the following way: when it is run as
a Dump conduit, it writes the to do list in order of decreasing priority
(I<i.e.>, priority 1 at the top, priority 5 at the bottom).

When it is run as a Fetch conduit, it assumes that the list is in order of
decreasing priority. If your file contains items

	- Existing item
	- New item

and C<Existing item> has a priority of 3, then C<New item> will be added
with a priority of 3 as well.

=head1 BUGS

It is not possible to set the indentation arguments to sane non-default
values.

Headers and footers are not preserved across runs.

Probably lots of boundary conditions. Whitespace, in particular, may not be
preserved exactly across runs.

=head1 SEE ALSO

coldsync(8)

=cut
#"

# This is for Emacs's benefit:
# Local Variables:	***
# fill-column:	75	***
# End:			***
